﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace YiYiTong.Rocket.Helper
{
    public class HttpHelper
    {
        /// <summary>
        /// 发生post请求
        /// </summary>
        /// <param name="contentType"> 
        /// http标头 
        /// application/x-www-form-urlencoded 
        /// application/xml
        /// application/json
        /// </param>
        /// <returns></returns>
        public static string HttpPost(string Url, string postDataStr, string contentType = "application/json")
        {
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            string retString = "";

            try
            {
                if (Url.ToLower().StartsWith("https"))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);//验证服务器证书回调自动验证
                    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
                }

                System.GC.Collect();
                request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "POST";
                request.KeepAlive = false;
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0";
                request.ProtocolVersion = HttpVersion.Version10;
                request.ContentType = contentType;
                byte[] bData = (Encoding.UTF8.GetBytes(postDataStr));
                request.ContentLength = bData.Length;
                Stream writeStream = request.GetRequestStream();
                writeStream.Write(bData, 0, bData.Length);
                writeStream.Close();

                using (response = (HttpWebResponse)request.GetResponse())
                {
                    Stream myResponseStream = response.GetResponseStream();
                    StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                    retString = myStreamReader.ReadToEnd();
                    myStreamReader.Close();
                    myResponseStream.Close();

                    return retString;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (request != null)
                    request.Abort();
                if (response != null)
                    response.Close();
            }
            return retString;
        }

        public static string WechatPost(string Url, string postDataStr, string certPath, string certPwd)
        {
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            string retString = "";

            try
            {
                if (Url.ToLower().StartsWith("https"))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);//验证服务器证书回调自动验证
                    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
                }

                System.GC.Collect();
                request = (HttpWebRequest)WebRequest.Create(Url);
                if (Url.ToLower().StartsWith("https"))
                {
                    X509Certificate2 cer = new X509Certificate2(certPath, certPwd, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
                    request.ClientCertificates.Add(cer);
                }
                request.Method = "POST";
                request.KeepAlive = false;
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0";
                request.ProtocolVersion = HttpVersion.Version10;
                request.ContentType = "application/xml";
                byte[] bData = (Encoding.UTF8.GetBytes(postDataStr));
                request.ContentLength = bData.Length;
                Stream writeStream = request.GetRequestStream();
                writeStream.Write(bData, 0, bData.Length);
                writeStream.Close();

                using (response = (HttpWebResponse)request.GetResponse())
                {
                    Stream myResponseStream = response.GetResponseStream();
                    StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                    retString = myStreamReader.ReadToEnd();
                    myStreamReader.Close();
                    myResponseStream.Close();

                    return retString;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (request != null)
                    request.Abort();
                if (response != null)
                    response.Close();
            }
            return retString;
        }

        /// <summary>
        /// 带http请求头post请求
        /// 作者：leev 
        /// 时间：2017-07-03
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="headerHt">请求头参数Hashtable对象</param>
        /// <param name="postData">post提交数据</param>
        /// <param name="contentType"> 
        /// http标头 
        /// application/x-www-form-urlencoded 
        /// application/xml
        /// application/json
        /// </param>
        /// <returns></returns>
        public static string SendPost(string url, Hashtable headerHt, string postData, ref string sign)
        {
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            string retString = "";
            try
            {
                if (url.ToLower().StartsWith("https"))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);//验证服务器证书回调自动验证
                    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
                }

                System.GC.Collect();
                request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.Accept = "zh-cn";
                //请求头参数
                if (headerHt.Count > 0)
                {
                    InheritWebHeaders headers = new InheritWebHeaders();
                    foreach (DictionaryEntry item in headerHt)
                    {
                        headers.AddHeaderWithoutValidate(item.Key.ToString(), item.Value.ToString());
                    }
                    request.Headers = headers;
                }
                request.KeepAlive = false;
                request.ProtocolVersion = HttpVersion.Version10;
                request.ContentType = "application/x-www-form-Urlencoded;charset=utf-8";
                byte[] bData = (Encoding.UTF8.GetBytes(postData));
                request.ContentLength = bData.Length;
                Stream writeStream = request.GetRequestStream();
                writeStream.Write(bData, 0, bData.Length);
                writeStream.Close();

                using (response = (HttpWebResponse)request.GetResponse())
                {
                    if (response.Headers.AllKeys.Contains("x-apsignature"))
                        sign = response.Headers["x-apsignature"].ToString();
                    Stream myResponseStream = response.GetResponseStream();
                    StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                    retString = myStreamReader.ReadToEnd();
                    myStreamReader.Close();
                    myResponseStream.Close();

                    return retString;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (request != null)
                    request.Abort();
                if (response != null)
                    response.Close();
            }
            return retString;
        }

        /// <summary>
        /// 发生get请求
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public static string HttpGet(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

        public class InheritWebHeaders : WebHeaderCollection
        {
            /*
            define your properties & methods here. -- by Mitchell Chu
            */
            public void AddHeaderWithoutValidate(
                string name
                , string value)
            {
                base.AddWithoutValidate(name, value);
            }
        }
        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {   // 总是接受  
            return true;
        }
    }
}
